package com.fireway;

import java.util.NoSuchElementException;

/**
 * 单链表
 * 2018年 04月 26日 星期四
 *
 * @author fireway
 */
public class SingleLinkedList<E> {
    private Entry<E> mHeader;  // 表头

    public SingleLinkedList() {
        mHeader = null;
    }

    /**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        Entry<E> newEntry = new Entry<E>(e, mHeader);    // newEntry --> old Entry
        mHeader = newEntry;                              // mHeader --> newEntry
    }

    /**
     * Removes and returns the first element from this list.
     *
     * @return the first element from this list
     */
    public E removeFirst() {
        if (empty()) {
            throw new NoSuchElementException();
        } else {
            Entry<E> tmp = mHeader;
            E result = tmp.mElement;
            mHeader = tmp.mNext;
            return result;

        }
    }

    public boolean empty() {
        // 当mHeader的值为null，就表明链表中没有数据项。
        // 如果有，mHeader应该存有对第一个链接点
        // 的引用值。
        return null == mHeader;
    }

    private static class Entry<E> {
        E mElement;
        Entry<E> mNext;

        public Entry(E element, Entry<E> next) {
            mElement = element;
            mNext = next;
        }
    }
}
